const { getDb } = require('../database');

function generateRandomNewsData(count) {
  const data = [];
  const classRealValues = [1, 2, 3, 4, 5];
  const sources = ['新华社', '人民日报', '央视新闻', '中国日报', '光明日报', '科技日报', '经济日报', '中国青年报'];
  const keywords = ['科技创新', '经济发展', '文化交流', '环境保护', '教育改革', '医疗进步', '体育赛事', '国际合作', '振兴乡村', '城市建设'];

  const now = new Date();
  const dateString = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`;

  for (let i = 1; i <= count; i++) {
    const keyword = keywords[Math.floor(Math.random() * keywords.length)];
    const action = ['取得重大突破', '迎接新机遇', '开启新篇章', '面临新挑战', '呈现新态势', '展现新活力', '获得新进展', '进入新阶段'][Math.floor(Math.random() * 8)];
    const coverImage = `https://placehold.co/600x400?text=${encodeURIComponent(keyword)}`;
    const source = sources[Math.floor(Math.random() * sources.length)];
    const classReal = classRealValues[Math.floor(Math.random() * classRealValues.length)];
    const newsTitle = `${keyword}${action}`;
    const abstract = `${keyword}最新动态：${action}`;

    data.push({
      abstract_real: abstract,
      class_real: classReal,
      news_title: newsTitle,
      news_source: source,
      news_time: dateString,
      cover_image: coverImage,
      is_select: 0,
      mark_content: `### ${newsTitle}\n\n${abstract}\n\n> 分类：${classReal}\n\n![封面图](${coverImage})\n\n本条目由定时任务自动生成，用于演示与测试。`
    });
  }
  return data;
}

async function insertMockNewsData() {
  try {
    const count = Math.floor(Math.random() * 6) + 5; // 每天插入 5-10 条
    const mockData = generateRandomNewsData(count);
    const db = await getDb();

    await db.run('BEGIN TRANSACTION');
    try {
      const stmt = await db.prepare(
        'INSERT INTO news (abstract_real, class_real, news_title, news_source, news_time, cover_image, is_select, mark_content) VALUES (?, ?, ?, ?, ?, ?, ?, ?)'
      );
      for (const item of mockData) {
        await stmt.run(
          item.abstract_real,
          item.class_real,
          item.news_title,
          item.news_source,
          item.news_time,
          item.cover_image,
          item.is_select,
          item.mark_content
        );
      }
      await stmt.finalize();
      await db.run('COMMIT');
      const totalCount = await db.get('SELECT COUNT(*) as count FROM news');
      console.log(`[news-mock] 插入 ${count} 条模拟新闻；当前总数：${totalCount.count}`);
    } catch (err) {
      await db.run('ROLLBACK');
      throw err;
    }
  } catch (error) {
    console.error('[news-mock] 插入模拟新闻出错:', error.message);
  }
}

function scheduleDailyMockNewsInsertion() {
  console.log('[news-mock] 定时任务已启用：将每天插入 5-10 条模拟新闻');
  // 服务器启动后先执行一次
  insertMockNewsData();
  // 之后每天执行一次
  const DAY_MS = 24 * 60 * 60 * 1000;
  setInterval(insertMockNewsData, DAY_MS);
}

module.exports = {
  scheduleDailyMockNewsInsertion
};